﻿using JV.Com.Business;
using JV.Com.Internals;
using JV.Com.Model;
using JV.Com.Tools;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JV.Com.ViewModels
{
    public sealed class FlipViewFullScreenPageViewModel : PageBaseViewModel
    {
        private readonly ObservableCollection<string> m_images;
        public FlipViewFullScreenPageViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            m_images = new ObservableCollection<string>();
        }

        public async override void OnNavigatedTo(object navigationParameter, Windows.UI.Xaml.Navigation.NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);
            InLoading = true;
            await ResolveUrlAsync((string)navigationParameter);
            InLoading = false;
        }

        private async Task ResolveUrlAsync(string imageUrl)
        {
           if (!imageUrl.StartsWith("http"))
            {
                var url = imageUrl.Remove(0, 5);

                // 01. Récupération des screen des jeux
                if (url.StartsWith("01.jeux"))
                {
                    var urlSplit = url.Split('/');
                    var lastSplit = urlSplit[urlSplit.Length - 1].Split('#');
                    var id = int.Parse(lastSplit[0].Replace(".xml", ""));
                    var screenId = int.Parse(lastSplit[lastSplit.Length - 1].Replace("num_", ""));

                    var game = await Service.GetGameAsync(id);
                    await Service.FillGameScreenshotsAsync(game);

                    int counter = 0;
                    foreach (var screen in game.LargeScreenshots)
                    {
                        m_images.Add(screen.Value);
                        if(screen.Key == screenId)
                        {
                            SelectedImageIndex = counter;
                        }
                        counter++;
                    }
                    
                    m_pageTitle = game.Title;
                    OnPropertyChanged("PageTitle");
                }
                // 02. Images de profil des auteurs, on s'en fou donc on ajoute l'image par défaut
                else if (url.StartsWith("profil"))
                {
                    m_images.Add(imageUrl);
                    SelectedImageIndex = 0;
                }
                else if(url.StartsWith("03.dossier"))
                {
                    var urlSplit = url.Split('/');
                    var lastSplit = urlSplit[urlSplit.Length - 1].Split('#');

                    var id = int.Parse(urlSplit[urlSplit.Length - 2]);
                    var screenUrl = lastSplit[0].Replace(".xml", "");
                    var screenId = int.Parse(lastSplit[lastSplit.Length - 1].Replace("num_", ""));

                    var folder = await Service.GetFolderAsync(id);
                    await Service.FillFolderScreenshotAsync(folder, screenUrl);

                    int counter = 0;
                    foreach (var screen in folder.LargeScreenshots)
                    {
                        m_images.Add(screen.Value);
                        if(screen.Key == screenId)
                        {
                            SelectedImageIndex = counter;
                        }
                        counter++;
                    }

                    m_pageTitle = folder.Title;
                    OnPropertyChanged("PageTitle");
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
            else
            {
                m_images.Add(imageUrl);
                SelectedImageIndex = 0;
            }

            TotalImages = m_images.Count;
        }

        private int m_selectedImageIndex;
        public int SelectedImageIndex
        {
            get { return m_selectedImageIndex; }
            set { SetProperty<int>(ref m_selectedImageIndex, value); OnPropertyChanged("SelectedImagePrintedIndex"); }
        }

        public int SelectedImagePrintedIndex { get { return m_selectedImageIndex + 1; } }

        private int m_totalImages;
        public int TotalImages
        {
            get { return m_totalImages; }
            set { SetProperty<int>(ref m_totalImages, value); }
        }

        public ObservableCollection<string> Images { get { return m_images; } }

        private string m_pageTitle;
        public override string PageTitle { get { return m_pageTitle; } }

        //private async Task ResolveUrlsAsync(IEnumerable<string> images)
        //{
        //    var imagesResolved = new List<ImageResolved>();

        //    var gamesToLoad = new Dictionary<int, Game>();
        //    var screenToLoad = new Dictionary<int, List<int>>();
        //    foreach (var image in images)
        //    {
        //        if(!image.StartsWith("http"))
        //        {
        //            // 01. Récupération des screen des jeux
        //            if(image.Contains("jeux/screen"))
        //            {
        //                var urlSplit = image.Split('/');
        //                var lastSplit = urlSplit[urlSplit.Length - 1].Split('#');
        //                var id = int.Parse(lastSplit[0].Replace(".xml", ""));
        //                var screenId = int.Parse(lastSplit[lastSplit.Length - 1].Replace("num_", ""));

        //                if (!gamesToLoad.ContainsKey(id))
        //                {
        //                    gamesToLoad.Add(id, new Game() { Id = id });
        //                }

        //                imagesResolved.Add(new ImageResolved() { DefineUrl = image, GameId = id, ScreenId = screenId });
        //            }
        //            // 02. Images de profil des auteurs, on s'en fou donc on ajoute l'image par défaut
        //            else if (image.Contains("profil"))
        //            {
        //                imagesResolved.Add(new ImageResolved() { DefineUrl = image, RealUrl = image });
        //            }
        //            else
        //            {
        //                throw new NotImplementedException();
        //            }
        //        }
        //        else
        //        {
        //            imagesResolved.Add(new ImageResolved() { DefineUrl = image, RealUrl = image });
        //        }
        //    }

        //    var tasks = gamesToLoad.Values.Select(async g =>
        //        {
        //            await Service.FillGameScreenshotsAsync(g);
        //        });
        //    await Task.WhenAll(tasks);

        //    foreach(var image in imagesResolved)
        //    {
        //        if(string.IsNullOrEmpty(image.RealUrl))
        //        {
        //            if(image.GameId.HasValue && image.ScreenId.HasValue)
        //            {
        //                image.RealUrl = gamesToLoad.First(g => g.Key == image.GameId.Value).Value.LargeScreenshots[image.ScreenId.Value];
        //            }
        //            else
        //            {
        //                throw new NotImplementedException();
        //            }
        //        }
        //    }

        //    foreach(var image in imagesResolved)
        //    {
        //        m_images.Add(image.RealUrl);
        //    }
        //}
    }
}
